package com.lihongman.web;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.lihongman.dao.UserDao;
import com.lihongman.entity.User;
import com.lihongman.util.StringUtil;


public class UserServlet extends HttpServlet {

	
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		
		String	task = request.getParameter("task");
		
		if(StringUtil.isEmpty(task)){
			tologin(request,response);
		}else if("login".equals(task)){
			login(request,response);
		}
		
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String name = request.getParameter("username");
		String pwd = request.getParameter("password");
		
		UserDao dao = new UserDao();
		User user = dao.findByNameAndPwd(name,pwd);
		
		HttpSession session  = request.getSession();
		if(user != null){
			session.setAttribute("user", user);
			
				response.sendRedirect("message.html");
			
		}else{
			response.sendRedirect("index.jsp?task=-100");
		}
		
	}

	private void tologin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request, response);
		
	}

	
}
